package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 用户下单
     * @param orderSubmitDto
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO orderSubmitDto) {
        //判断地址簿是否为空
        AddressBook addressBook = addressBookMapper.getById(orderSubmitDto.getAddressBookId());
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //判断当前用户购物车的数据
        Long userId = BaseContext.getCurrentId(); //获取当前用户id
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if(list == null || list.size() == 0){
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderSubmitDto,orders); //拷贝DTO的数据到orders对象中
        //设置DTO中没有的数据
        BeanUtils.copyProperties(orderSubmitDto, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);

        orderMapper.insert(orders); //插入到订单表中

        //向订单明细表插入n条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail(); //创建订单明细对象
            //赋值
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId()); //设置订单id
            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetailList);
        //清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);

        //封装VO对象返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 历史订单查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQueryUser(Integer page, Integer pageSize, Integer status) {
        //设置分页
        PageHelper.startPage(page,pageSize);

        //根据参数查询订单表
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId()); //设置用户id
        ordersPageQueryDTO.setStatus(status); //设置订单状态

        Page<Orders> list =  orderMapper.pageQuery(ordersPageQueryDTO); //根据参数查询订单表

        List<OrderVO> orderVOList = new ArrayList<>();
        //根据订单表的id查询订单明细表数据
        if(list != null || list.getTotal() > 0){
            for (Orders orders : list) {
                Long id = orders.getId();
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id); //根据订单表的id查询订单明细表数据
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);

                orderVO.setOrderDetailList(orderDetails);
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(list.getTotal(),orderVOList);
    }

    /**
     * 根据id查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Integer id) {
        //根据id查询订单
        Orders orders =  orderMapper.getById(id);

        //查询订单id对应的菜品/套餐明细
        Long ordersId = orders.getId();
        List<OrderDetail> orderVOList =  orderDetailMapper.getByOrderId(ordersId);

        //将订单信息和订单明细封装在orderVO中并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderVOList);

        return orderVO;
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryAdmin(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO){
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        //订单号
        String orderNumber = ordersPaymentDTO.getOrderNumber();

        //这里我们需要根据订单号查询订单，需要创建一个对象去数据库查询，而且最后我们更新这个对象属性，再使用update就ok
        Orders order = orderMapper.getByNumberAndUserId(orderNumber,userId);
        order.setPayStatus(Orders.PAID);
        order.setStatus(Orders.TO_BE_CONFIRMED);
        order.setCheckoutTime(LocalDateTime.now());
        orderMapper.update(order);

        //我们接口返回的数据，可以看一下属性类的结构，里面的数据都是最后调用微信支付使用到的，我们用不到那里，直接返回空数据就行
        OrderPaymentVO vo = new OrderPaymentVO();

        //
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒.
        map.put("orderId", order.getId());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        return vo;
    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 根据订单id取消订单
     * @param id
     * @return
     */
    @Override
    public void userCancelOrder(Integer id) {
        Orders orders = orderMapper.getById(id);//根据id查询订单

        //查看订单是否存在
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //当订单处于已接单或之后 则不能退款
        if(orders.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //如果订单处于待接单 需要进行退款
        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //订单支付状态修改为已退款
            orders.setPayStatus(Orders.REFUND);

            orders.setStatus(Orders.CANCELLED); //订单状态修改为已取消
            orders.setCancelReason("用户取消"); //订单取消原因
            orders.setCancelTime(LocalDateTime.now()); //订单取消时间
        }
        //更新订单数据
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     * @return
     */
    @Override
    public void repetition(Long id) {
        //根据订单id查询订单明细表
        List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(id);

        //将订单明细表集合转换成购物车对象集合
        List<ShoppingCart> shoppingCartList = orderDetail.stream().map(order ->{
            ShoppingCart shoppingCart = new ShoppingCart(); //创建一个购物车对象

            BeanUtils.copyProperties(order,shoppingCart,"id"); //id为自增键 不拷贝
            shoppingCart.setUserId(BaseContext.getCurrentId()); //设置用户id
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        //将集合批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //统计 待派送数量、派送中数量、待接单数量
        Integer confirmed = orderMapper.count(Orders.CONFIRMED); //待派送数量
        Integer deliveryInProgress = orderMapper.count(Orders.DELIVERY_IN_PROGRESS); //派送中数量
        Integer toBeConfirmed = orderMapper.count(Orders.TO_BE_CONFIRMED); //待接单数量

        //封装对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @return
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED) //修改订单状态
                .build();
        orderMapper.update(orders);
    }

    /**
     * 接单
     * @param id
     * @return
     */
    @Override
    public void delivery(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     *
     * @param id
     * @return
     */
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     * @return
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     * @return
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     * @return
     */
    @Override
    public void reminder(Integer id) {
        //查询订单信息
        Orders orders = orderMapper.getById(id);
        //查看订单是否存在
        if(orders ==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号" + orders.getNumber());

        //通过websocket向客户端推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}